from odoo import fields, models, api


class ProductPriorityLine(models.Model):
    _name = 'product.priority.line'
    _description = '物料优先级明细'

    rule_id = fields.Many2one('product.replace.rule', string='产品替换规则')
    priority_domain = fields.Char(string='物料优先级筛选条件')
    sequence = fields.Integer(default=10, string="优先级")
    sort_field = fields.Many2one('ir.model.fields', string='排序字段')
    sort_field_lvt = fields.Many2one('ir.model.fields', string='排序字段')
    model_name = fields.Char(string='模型', compute='_compute_model_name', store=True)
    sort_field_display = fields.Char(string='排序字段', compute='_compute_sort_field_display', store=True)
    is_lvt = fields.Boolean(string='排序涉及第二层', default=False)
    reverse = fields.Boolean(string='倒序', default=False)

    @api.depends('is_lvt')
    def _compute_model_name(self):
        for rec in self:
            if rec.is_lvt:
                rec.model_name = rec.sort_field.relation
            else:
                rec.model_name = False

    @api.depends('sort_field', 'sort_field_lvt', 'reverse')
    def _compute_sort_field_display(self):
        for rec in self:
            if rec.sort_field and rec.sort_field_lvt:
                sort_field_display = f'{rec.sort_field.field_description}-{rec.sort_field_lvt.field_description}'
            elif rec.sort_field:
                sort_field_display = f'{rec.sort_field.field_description}'
            else:
                sort_field_display = ''
            if rec.reverse:
                sort_field_display += ' 倒序'
            rec.sort_field_display = sort_field_display

    @api.onchange('sort_field')
    def _onchange_sort_field(self):
        if self.sort_field.ttype in ['one2many', 'many2many', 'many2one']:
            self.is_lvt = True
        else:
            self.sort_field_lvt = False
            self.is_lvt = False

    _sql_constraints = [
        ('product_uniq', 'unique (product_id)', "该产品替换规则已存在."),
    ]

